package com.platform.api.bzproject.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.api.bzproject.model.BzIntegralRecord;
import com.platform.api.bzproject.model.User;
import com.platform.api.bzproject.service.IBzIntegralRecordService;
import com.platform.api.bzproject.service.UserService;
import com.platform.common.core.Result;
import com.platform.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 积分表 前端控制器
 * </p>
 *
 * @author guoshao
 * @since 2021-11-06
 * 源码联系微信：2549789059
 */
@RestController
@RequestMapping("{appid}/p/integral")
public class BzIntegralRecordController {

    @Autowired
    private IBzIntegralRecordService iBzIntegralRecordService;

    @Autowired
    private UserService userService;

    @PostMapping("addIntegra")
    public Result addIntegra(@RequestBody BzIntegralRecord bzIntegralRecord){


        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                bzIntegralRecord.setOpenid(userId);
            }
        }catch (Exception e){

        }

        bzIntegralRecord.setCreateTime(new Date());

        iBzIntegralRecordService.save(bzIntegralRecord);

        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", bzIntegralRecord.getOpenid()).last("limit 1"));

        if(null != user){
            Integer integral = null == user.getScore() ? 0 : user.getScore();

            Integer integral1 = bzIntegralRecord.getIntegral();

            user.setScore(integral + integral1);

            userService.updateById(user);
        }
        return Result.success(user.getScore());
    }

    @GetMapping("getIntegra")
    public Result getIntegra(){

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();

        }catch (Exception e){

        }
        if(StringUtils.isNotBlank(userId)){
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId).last("limit 1"));
            return Result.success(null != user ? (null != user.getScore() ? user.getScore() : 0) : 0);
        }
        return Result.success(0);
    }


}
